package common.newstream;

import com.google.common.collect.Lists;
import lombok.Data;
import org.springframework.util.StopWatch;

import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @author: kanggw
 * @date: 2022/3/10
 * @DESCRIPTION:　Java Stream API中多个和单个filter有性能差异吗？
 */
public class StreamFilterDemo {


    public static void main(String[] args) {
//        filterOne();

        filterTwo();
    }

    private static void filterTwo() {
        List<Employee> employees = Lists.newArrayList();

        for (int i = 1; i <= 100000; i++) {
            Employee employee = new Employee();

            employee.setAge(i % 100);
            employee.setGender(i % 2 == 0 ? "male" : "female");

            employees.add(employee);
        }

        StopWatch watch = new StopWatch();

        watch.start();
        employees.stream()
                 .filter(employee -> employee.getAge() > 32)
                 .filter(employee -> "male".equals(employee.getGender()))
                 .collect(Collectors.toList());
        watch.stop();
        System.out.println(watch.getTotalTimeMillis());
    }

    private static void filterOne() {
        List<Employee> employees = Lists.newArrayList();

        for (int i = 1; i <= 100000; i++) {
            Employee employee = new Employee();

            employee.setAge(i % 100);
            employee.setGender(i % 2 == 0 ? "male" : "female");

            employees.add(employee);
        }

        StopWatch watch = new StopWatch();

        watch.start();
        employees.stream()
                 .filter(employee ->
                         employee.getAge() > 32
                                 && "male".equals(employee.getGender()))
                 .collect(Collectors.toList());
        watch.stop();
        System.out.println(watch.getTotalTimeMillis());
    }

    @Data
    static class Employee {
        private String gender;
        private Integer age;
    }

}
